﻿using UnityEngine;
using UnityEditor;
using UnityEngine.SceneManagement;

public class MaterialInstanceFixer : MonoBehaviour
{
    [MenuItem("TA/辅助/还原材质（Instance）问题")]
    static void RevertMaterials()
    {
        Renderer[] renderers = FindObjectsOfType<Renderer>();
        foreach (Renderer renderer in renderers)
        {
            Material[] materials = renderer.sharedMaterials;
            for (int i = 0; i < materials.Length; i++)
            {
                Material mat = materials[i];
                if (mat != null && string.IsNullOrEmpty(AssetDatabase.GetAssetPath(mat)))
                {
                    // 尝试从 Prefab 或场景中的原始对象恢复材质
                    GameObject prefabRoot = PrefabUtility.GetCorrespondingObjectFromSource(renderer.gameObject);
                    if (prefabRoot != null)
                    {
                        Renderer prefabRenderer = prefabRoot.GetComponent<Renderer>();
                        if (prefabRenderer != null)
                        {
                            materials[i] = prefabRenderer.sharedMaterials[i];
                        
                        }
                    }
                }
            }
            renderer.sharedMaterials = materials;
        }
        Debug.Log("Material restoration complete.");
    }
}